#!/usr/bin/env python3
import asyncio
import json
import logging
import websockets
from datetime import datetime

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 定义消息类型常量
PATIENT_REPORT = 'PATIENT_REPORT'
PATIENT_REPORT_RESPONSE = 'PATIENT_REPORT_RESPONSE'

class SimpleWebSocketServer:
    def __init__(self):
        self.clients = set()
        
    async def register(self, websocket):
        self.clients.add(websocket)
        logger.info(f"新客户端连接，当前连接数: {len(self.clients)}")
        
    async def unregister(self, websocket):
        self.clients.discard(websocket)
        logger.info(f"客户端断开连接，当前连接数: {len(self.clients)}")
        
    async def broadcast(self, message):
        if self.clients:
            await asyncio.gather(
                *[client.send(message) for client in self.clients],
                return_exceptions=True
            )
            
    async def handler(self, websocket, path):
        await self.register(websocket)
        try:
            async for message in websocket:
                try:
                    data = json.loads(message)
                    logger.info(f"收到消息: {data}")
                    
                    # 处理患者上报
                    if data.get('type') == PATIENT_REPORT:
                        response = {
                            'type': PATIENT_REPORT_RESPONSE,
                            'data': {
                                'status': 'success',
                                'timestamp': datetime.now().isoformat()
                            }
                        }
                        await self.broadcast(json.dumps(response))
                        
                except json.JSONDecodeError:
                    logger.error("消息格式错误")
                    
        except websockets.exceptions.ConnectionClosed:
            logger.info("连接正常关闭")
        finally:
            await self.unregister(websocket)

async def main():
    server = SimpleWebSocketServer()
    host = "0.0.0.0"
    port = 8080
    logger.info(f"启动WebSocket服务器: ws://{host}:{port}")
    
    async with websockets.serve(server.handler, host, port):
        logger.info("WebSocket服务器启动成功")
        await asyncio.Future()

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("服务器停止")
    except Exception as e:
        logger.error(f"服务器运行出错: {e}") 